package com.xiaomaoguai.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @fileName: NettyServer.java
 * @author: WeiHui
 * @date: 2018/9/30 14:50
 * @version: v1.0.0
 * @since JDK 1.8
 */
public class NettyServer {

	public static final int PORT = 8000;

	public static void main(String[] args) {

		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workGroup = new NioEventLoopGroup();

		ServerBootstrap bootstrap = new ServerBootstrap();

		bootstrap.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childOption(ChannelOption.SO_KEEPALIVE, true)
				.childOption(ChannelOption.TCP_NODELAY, true)
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new FirstChannelHandler());
					}
				});
		startUp(bootstrap, PORT);
	}

	private static void startUp(ServerBootstrap bootstrap, int port) {
		bootstrap.bind(port).addListener(f -> {
			if (f.isSuccess()) {
				System.out.println("启动成功");
			} else {
				System.out.println("启动失败");
				startUp(bootstrap, port + 1);
			}
		});
	}

}
